package com.adkun.community.controller;

import com.adkun.community.util.CommunityUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/alpha")
@Deprecated
public class AlphaController {

    @RequestMapping("/test")
    public String test() {
        return "/test";
    }

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello Sprint Boot.";
    }

    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) {
        // response对象可以直接向浏览器输出任何数据，不依赖于返回值
        // HttpServletRequest是常用的请求对象，HttpServletResponse是常用的响应对象

        // 获取请求数据
        System.out.println(request.getMethod()); // 获取请求方式（请求行）
        System.out.println(request.getServletPath()); // 获取请求路径（请求行）
        Enumeration<String> enumeration = request.getHeaderNames(); // 获取请求行，结构：(key,value)
        // Enumeration是一个很老的迭代器，现在一般不用了，但request对象一直用的是这个迭代器，所以没有变
        while (enumeration.hasMoreElements()) { // 请求消息头（若干行）
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ":" + value);
        }

        //获取请求体
        System.out.println(request.getParameter("code")); //获取name="code"的数据

        // 返回响应数据
        // response封装了输出流，即它可以自动输出到浏览器
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter writer = response.getWriter();) { // JAVA7新语法，在try()里新建对象，会自动加finally里面writer.close()
            writer.write("<h1>你好</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // GET
    // /students?current=1&limit=20  （第1页，最多显示20个数据）
    @RequestMapping(path = "/students", method = RequestMethod.GET)  //指定只有GET请求才能访问这个方法
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "20") int limit) {
        // 把参数命名为传入参数名一致即可
        // 若不一定要传参，则@RequestParam(name="",required=false,defaultValue="")
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    // /student/123
    // 根据路径查询一个学生，参数成为路径的一部分，即查询123号student
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        return "a student";
    }

    // POST 浏览器向服务器提交数据
    // 首先浏览器得打开一个带有表单的网页
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(
            @RequestParam(name = "name", required = false, defaultValue = "无") String name,
            @RequestParam(name = "age", required = false, defaultValue = "0") int age) {
        // 参数类型和表单一致
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    // 响应HTML数据
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher() {
        // 将ModelAndView传给view template就可以生成动态网页
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "张三");
        mav.addObject("age", 30);
        mav.setViewName("/demo/view"); //不用写后缀，默认为.html
        return mav;
    }

    // 另一种响应HTML数据的方式
    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        // 如果参数都有Model，则DispacherServlet会自动识别，传给model也可以
        model.addAttribute("name", "李四");
        model.addAttribute("age", 40);
        // 返回的String相当于ModelAndView的mav.setViewName("")
        return "/demo/view";
    }

    // 响应JSON数据（异步请求）
    // 通常在异步请求当中需要JSON
    // 比如要注册B站，要输入昵称，密码。当输入昵称后，切换焦点或光板切换时，判断用户名是否被占用了

    // JAVA对象 -> JSON字符串 -> JS对象
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 23);
        emp.put("salary", 8000.00);
        return emp;
        // 自动将Map转换为JSON字符串
    }

    // JSON，查询所有员工
    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 23);
        emp.put("salary", 9999.99);
        list.add(emp);

        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 50);
        emp.put("salary", 14888.98);
        list.add(emp);

        return list;
    }

    // cookie示例
    @RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        // Cookie在头部，和内容无关
        // 每一个cookie创建时必须有参数，每个cookie只能存一组字符串
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        // 设置Cookie失效的范围，即有效路径，无效路径就不发cookie
        cookie.setPath("/community/alpha"); // 设置/commuity/alpha以及子路径有效
        // 浏览器得到cookie后默认会存到内存里，关掉就消失。需要设置cookie失效时间
        cookie.setMaxAge(60 * 10); // 单位：秒

        //发送cookie
        response.addCookie(cookie);

        return "set cookie";
    }

    @RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
    @ResponseBody
    public String getCookie() {
        return "get cookie";
    }

    @RequestMapping(path = "/cookie/getall", method = RequestMethod.GET)
    @ResponseBody
    public String getCookies(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        Iterator<Cookie> itr = Arrays.stream(cookies).iterator();
        while (itr.hasNext()) {
            Cookie cookie = itr.next();
            String name = cookie.getName();
            String value = cookie.getValue();

            System.out.println("name:" + name);
            System.out.println("value:" + value);
        }
        return "get all cookies";
    }

    @RequestMapping(path = "/cookie/getone", method = RequestMethod.GET)
    @ResponseBody
    public String getACookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get a cookie";
    }

    // Session示例
    @RequestMapping(path = "/session/set", method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session) {
        // 服务器创建Session不用手动创建，Spring MVC可以自动创建
        // Session可以存任何类型的数据
        session.setAttribute("id", 1);
        session.setAttribute("name", "Test");
        return "set session";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

    // ajax示例
    @RequestMapping(path = "ajax", method = RequestMethod.POST)
    @ResponseBody //因为是异步请求，不向浏览器返回网页，返回的是字符串
    public String testAjax(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功！");
    }
}

